package com.demodis.interceptor;

import com.demodis.domain.Json;
import com.demodis.domain.TblUser;
import com.demodis.service.PermissionServiceI;
import com.demodis.service.impl.PermissionServiceImpl;
import com.demodis.util.Utils;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class PopedomInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -4172940868016111147L;

	PermissionServiceI permService = new PermissionServiceImpl();

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String result = null;
		TblUser user = (TblUser) invocation.getInvocationContext().getSession().get("user");
		String actionName = invocation.getInvocationContext().getName();
		String method = invocation.getProxy().getMethod();
		String permUrl = null;
		Json json = new Json();
		if ("execute".equals(method)) {
			permUrl = "/" + actionName + ".action";
		} else {
			permUrl = "/" + actionName + "!" + method + ".action";
		}
		if (user == null && !"/userAction!login.action".equals(permUrl)) {
			json.setSuccess(false);
			json.setMsg("请先登陆！");

			Utils.writeJson(json);
			result = null;
		} else if (user != null) {
			if ("admin".equals(user.getUsername()) && Utils.isPass(actionName)) {
				result = invocation.invoke();
			} else if (permService.existPerm(user.getUserId(), permUrl)) {
				result = invocation.invoke();
			} else {
				json.setSuccess(false);
				json.setMsg("权限不足!");

				Utils.writeJson(json);
				result = null;
			}
		} else {
			result = invocation.invoke();
		}

		return result;
	}

}
